package servlet;

import bean.AdInfo;
import bean.User;
import com.alibaba.fastjson.JSON;
import service.AdInfoService;
import service.UserService;

import java.io.*;
import java.util.Objects;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet", "/insertAdv", "/updateAdv", "/delAdv"})
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2,    // 2MB
        maxFileSize = 1024 * 1024 * 10,        // 10MB
        maxRequestSize = 1024 * 1024 * 50)    // 50MB
public class UpDoServlet extends HttpServlet {

    String imgPath = "";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");// 设置请求参数的编码格式
        response.setContentType("text/html;charset=utf-8");// 设置网页界面相应的代码

        // 获取请求 URI
        String requestURI = request.getRequestURI();
        UserService userService = new UserService();
        if (requestURI.endsWith("UploadServlet")) {
            // 获取上传的文件
            Part filePart = request.getPart("file");
            // 获取文件名
            String fileName = filePart.getSubmittedFileName();
            System.out.println("文件名为:"+fileName);
            // 获取服务器上的保存目录
            String savePath = "img/bubble/";
            System.out.println("保存路径为" + savePath);
            imgPath = savePath + fileName;
            File saveDir = new File(request.getServletContext().getRealPath("img/bubble"));
            // 保存文件到服务器
            OutputStream out = new FileOutputStream(new File(saveDir, fileName));
            InputStream fileContent = filePart.getInputStream();
            int read = 0;
            final byte[] bytes = new byte[1024];
            while ((read = fileContent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.close();
            fileContent.close();
            // 返回上传成功信息
            response.getWriter().println("文件 " + fileName + " 文件上传成功!");

        } else if (requestURI.endsWith("insertAdv")) {
            // 从请求体中获取 JSON 数据
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = request.getReader();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            System.out.println(imgPath);
            // 将 JSON 数据转换为 AdInfo 对象
            AdInfo adInfo = JSON.parseObject(stringBuilder.toString(), AdInfo.class);
            String byUsername = userService.getId(adInfo.getUser_id()); //根据id查询用户名
            adInfo.setAd_img(imgPath);  //设置图片路径
            adInfo.setUser_id(byUsername); //设置所属用户id
            AdInfoService adInfoService = new AdInfoService();
            adInfoService.insertAdsInfo(adInfo);
        } else if (requestURI.endsWith("updateAdv")) {
            // 从请求体中获取 JSON 数据
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = request.getReader();
            AdInfoService adInfoService = new AdInfoService();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            System.out.println("图片路径为：-----------------"+imgPath);
            // 将 JSON 数据转换为 AdInfo 对象
            AdInfo adInfo = JSON.parseObject(stringBuilder.toString(), AdInfo.class);
            String byUsername = userService.getId(adInfo.getUser_id()); //根据id查询用户名
            //设置所属用户id
            adInfo.setUser_id(byUsername);
            adInfo.setAd_img(imgPath);
            System.out.println("数据为:----------------" + adInfo);
            if (Objects.equals(imgPath, "")){
                System.out.println("修改操作无图片数据");
                adInfoService.updateAdsInfo(adInfo);
            }else {
                System.out.println("有图片文件数据："+adInfo.getAd_img());
                adInfoService.updateAdsInfo(adInfo);
                adInfoService.updateImg(imgPath,adInfo);
            }
            imgPath=""; //初始化图片路径
        } else if (requestURI.endsWith("delAdv")) {
            BufferedReader reader = request.getReader();
            String ad_id = reader.readLine();
            AdInfo adInfo = JSON.parseObject(ad_id, AdInfo.class);
            System.out.println("删除的信息为:" + adInfo.getAd_id());
            String adId = adInfo.getAd_id();
            AdInfoService adInfoService = new AdInfoService();
            adInfoService.delAdv(adId);
        }
    }
}
